<?php

namespace app\admin\controller\facrm\contract;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 回款计划
 *
 * @icon fa fa-circle-o
 */
class Plan extends Backend
{

    protected $noNeedRight = ["select"];
    /**
     * Plan模型对象
     * @var \app\admin\model\facrm\contract\Plan
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\contract\Plan;
        $config = get_addon_config('facrm');
        $this->view->assign("account_list", $config['account']);
        $this->assignconfig("account_list", $config['account']);
        $this->view->assign("status_list", $this->model->getStatusList());
        $this->assignconfig("status_list", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index($view = "")
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter_w = [];

            if (isset($filter['plan_time']) && strtotime($filter['plan_time'])) {
                $time = time();
                $filter_w['plan_time'] = ['<', \think\Db::raw(" ({$time}+(`remind_day`*86400))")];
                $filter_w['plan.status'] = ['neq', 2];
                unset($filter['plan_time']);
                $this->request->get(['filter' => json_encode($filter)]);
            }


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            if (!$this->auth->isSuperAdmin() && !$this->auth->check('facrm/contract/index/index')) {
                $this->model->where('contract.order_admin_id', 'in', $this->auth->getChildrenAdminIds(true));
            }

            $list = $this->model
                ->with(['contract', 'customer', 'admin'])
                ->where($where)
                ->where($filter_w)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('contract')->visible(['name', 'id', 'number']);
                $row->getRelation('customer')->visible(['name', 'id']);
                $row->getRelation('admin')->visible(['nickname', 'id']);

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch($view);
    }


    public function add($contract_id = NULL)
    {

        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if (empty($params)||!isset($params['contract_id'])) {
                $this->error(__('Parameter %s can not be empty', ''));
            }

            $auth = new \addons\facrm\library\Auth();
            if (!$auth->checkContractAuth($params['contract_id'], $this->auth, 'all')) {
                $this->error(__('您没有该合同的权限'));
            }

            $params['admin_id'] = $this->auth->id;
            $this->request->post(['row' => $params]);
            return parent::add();
        }
        if ($contract_id) {
            $contractModel = new \app\admin\model\facrm\Contract();
            $contract = $contractModel->find($contract_id);
            $this->view->assign('contract_r', $contract);
        }

        return $this->view->fetch('add', ['addtype' => 'add']);
    }

    /**
     * 修改
     * @param null $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function edit($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!$this->auth->isSuperAdmin() && !$this->auth->check('facrm/contract/index/index') && !in_array($row->contract->order_admin_id, $this->auth->getChildrenAdminIds(true))) {
            $this->error(__('您没有权限修改'));
        }

        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 选择回款计划
     */
    public function select($contract_id)
    {
        $contractModel = model('\app\admin\model\facrm\Contract');
        $contract = $contractModel->find($contract_id);
        if (!$contract) {
            $this->error(__('合同不存在'));
        }
        $auth = new \addons\facrm\library\Auth();
        if (!$auth->checkContractAuth($contract, $this->auth, 'all')) {
            $this->error(__('您没有该合同的权限'));
        }
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $filter = $this->request->request('filter');
        $filterArr = (array)json_decode($filter, true);
        $filterArr['contract_id'] = $contract_id;
        $this->request->get(['filter' => json_encode($filterArr)]);

        return $this->index('index');


    }

}
